from kubernetes import client, config


def get_container_stats(namespace):
    # 加载 kubeconfig 文件，如果没有指定，则使用默认的 kubeconfig 文件
    config.load_kube_config()

    # 创建 CustomObjectsApi 的实例，用于与集群通信
    api_instance = client.CustomObjectsApi()

    # 定义 Metrics API 的组、版本和资源路径
    group = 'metrics.k8s.io'
    version = 'v1beta1'
    resource_path = 'pods'

    # 发起请求获取指定命名空间中的所有 Pod 的 Metrics
    pods_metrics = api_instance.list_namespaced_custom_object(group, version, namespace, resource_path)
    data = {
    }
    # 遍历每个 Pod 的 Metrics，并打印容器的资源使用情况
    def convert_cpu(cpu_usage):
        return "{:.4g}".format(int(cpu_usage[:-1]) / 1000000) if cpu_usage[:-1]!='' else '0'  # 将 nanocores 转换为 millicores，并保留四位有效数字

    def convert_memory(memory_usage):
        return "{:.4g}".format(int(memory_usage[:-2]) / 1024) if memory_usage[:-2]!='' else '0'  # 将 KiB 转换为 MiB，并保留四位有效数字
    data = {}
    for pod_metric in pods_metrics['items']:
        pod_name = pod_metric['metadata']['name']
        containers_metrics = pod_metric['containers']
        for container_metric in containers_metrics:
            container_name = container_metric['name']
            cpu_usage = container_metric['usage']['cpu']
            memory_usage = container_metric['usage']['memory']
            print(f"Pod: {pod_name}, Container: {container_name}, CPU: {(cpu_usage)}, Memory: {(memory_usage)}")
            data[pod_name] = {
                "container_name": container_name,
                "cpu": convert_cpu(cpu_usage),
                "memory": convert_memory(memory_usage)
            }
    return data

if __name__ == "__main__":
    data = get_container_stats("default")
    print (data)
